<template>
  <t-table
    row-key="serial-number"
    :columns="props.columns"
    :data="props.tableData"
    :empty="fieldNoDataText"
    :showHeader="props.showHeader"
  >
    <template #[item.colKey]="{ row, rowIndex }" v-for="item in editColumns">
      <component
        v-if="item.edit?.el && item.edit?.el !== 'slot'"
        :is="`t-${item.edit.el}`"
        v-model="props.tableData[rowIndex][item.colKey]"
        v-bind="item.edit?.props"
      >
        <template v-if="item.edit.el === 'select'">
          <component
            :is="`t-option`"
            v-for="(col, index) in enumMap.get(item.colKey ?? '')"
            :key="index"
            :label="col[fieldNames(item).label]"
            :value="col[fieldNames(item).value]"
          ></component>
        </template>
      </component>
      <slot :name="item.colKey" :row="row" :rowIndex="rowIndex" v-else></slot>
    </template>
    <template #operate="{ rowIndex }">
      <t-button
        theme="default"
        shape="square"
        class="margin-right"
        @click="addTableData()"
        :style="'opacity:' + (rowIndex == tableData.length - 1 ? 1 : 0)"
      >
        <AddIcon slot="icon" class="color-primary" />
      </t-button>
      <t-button
        theme="default"
        shape="square"
        @click="
          () => {
            tableData.splice(rowIndex, 1);
          }
        "
      >
        <RemoveIcon slot="icon" class="color-warning" />
      </t-button>
    </template>
  </t-table>
</template>
<script lang="tsx" setup>
import { ref } from 'vue';
import { AddIcon, RemoveIcon } from 'tdesign-icons-vue-next';
import { type BaseTableProps } from 'tdesign-vue-next';
import { type ColumnProps } from '@/components/Table/interface';
import { cloneDeep } from 'lodash';
interface TreTableProps extends Partial<Omit<BaseTableProps, 'data'>> {
  columns: ColumnProps[]; // 列配置项==> 必传
  tableData?: { [key: string]: any }[]; //==> 非必传
  showHeader?: boolean; //是否显示表头==> 非必传（默认为true）
  initDataField?: {};
}

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<TreTableProps>(), {
  columns: () => [],
  showHeader: true,
  tableData: () => [],
});

// 接收 columns 并设置为响应式
const tableColumns = ref<ColumnProps[]>(props.columns);

// 定义 enumMap 存储 enum 值
const enumMap = ref(new Map<string, { [key: string]: any }[]>());

// 扁平化 columns
const flatColumnsFunc = (
  columns: ColumnProps[],
  flatArr: ColumnProps[] = [],
) => {
  columns.forEach(async col => {
    flatArr.push(col);

    // 如果当前 enum 为后台数据需要请求数据，则调用该请求接口，并存储到 enumMap
    if (!col.enum) return;
    if (typeof col.enum !== 'function')
      return enumMap.value.set(col.colKey!, col.enum);
    const { data } = await col.enum();
    enumMap.value.set(col.colKey!, data.data);
  });
  return flatArr;
};

// flat columns
const flatColumns = ref<ColumnProps[]>();
//@ts-ignore
flatColumns.value = flatColumnsFunc(tableColumns.value);

// 过滤需要编辑的配置项
const editColumns: any = flatColumns.value.filter(item => item.edit?.el);
// 判断 fieldNames 设置 label && value 的 key 值
const fieldNames = (column: ColumnProps) => {
  return {
    label: column.fieldNames?.label ?? 'label',
    value: column.fieldNames?.value ?? 'value',
  };
};

const fieldNoDataText = () => (
  <t-button theme="default" shape="square" onClick={addTableData}>
    {/* <AddIcon slot="icon" class="color-primary" /> */}
    <AddIcon class="color-primary" />
  </t-button>
);

const addTableData = () => {
  props.tableData.push(
    props.initDataField ? cloneDeep(props.initDataField) : {},
  );
};
// 暴露给父组件使用
defineExpose({ enumMap });
</script>
